/* -----------------
* brief
* 1. this is code gen by tools
 */

package service

import (
	"errors"
	"fmt"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"saas_sys_base/common"
	"time"
)
import . "saas_sys_base/modules/appmanager/models"

type AppTenantPermissionService struct {
	// add your model here
	tbAppTenantPermission AppTenantPermission
}

func (t *AppTenantPermissionService) ListAppTenantPermission(keyword string, page, psize int) ([]map[string]string, int64, error) {
	// 业务查询
	queryMap := map[string]interface{}{
		"table":  map[string]string{"table": "tb_app_tenant_permission", "alias": "t1"},
		"fields": []string{"t1.*"},
		"join":   []map[string]string{
			// map[string]string{"table": "tb_xx as t2", "on": "t2.xid = t1.id"},
		},
		"where": []lego.QMapWhereField{
			//{"t1.if_del", "=", 0, "AND", false},
		},
		"search": map[string]string{
			//"t1.id": req.Keyword,
		},
		"orders": []string{"t1.id asc"},
		"page": map[string]int{
			"page":  page,
			"psize": psize,
		},
	}
	return lego.QueryListByMap(queryMap)
}

/* 根据id获取记录
 * -----------------
 */
func (t *AppTenantPermissionService) GetAppTenantPermissionById(id int64) *AppTenantPermission {
	return t.tbAppTenantPermission.RecodeById(id)
}

/* 根据id获取记录
 * -----------------
 */
func (t *AppTenantPermissionService) GetAppTenantPermissionByWho(who *common.Who) *AppTenantPermission {
	return t.tbAppTenantPermission.RecodeByWho(who)
}

/* 添加
 * -----------------
 */
func (t *AppTenantPermissionService) SaveAppTenantPermission(item2add *AppTenantPermission) bool {
	return t.tbAppTenantPermission.AddRecode(item2add)
}

/* 删除(硬删除)*/
func (t *AppTenantPermissionService) DelAppTenantPermissionById(id int64) bool {
	return t.tbAppTenantPermission.DelRecodeById(id)
}

/* 更新
 * -----------------*/
func (t *AppTenantPermissionService) UpdateAppTenantPermission(rc *AppTenantPermission) bool {
	return t.tbAppTenantPermission.UpdateRecode(rc)
}

//自定义函数
/*
增加对应app的过期时间
*/
func (t *AppTenantPermissionService) AddAppPermissionForExpireTime(appwho *common.Who, miniAppIdForSale int64, addTimeYmd utils.YearMonthDays, checkMode common.CHECK_MODE) (*AppTenantPermission, error) {

	if checkMode != common.APP_PERMISSION_CHECK_MODE_DATATIME &&
		checkMode != common.APP_PERMISSION_CHECK_MODE_DATETIME2 {
	    return nil, fmt.Errorf("not support checkMode<%d>", checkMode)
	}

	// TODO 设置哪个app
	session := lego.GetDBEngine().NewSession()
	defer session.Close()

	err := session.Begin()
	if err != nil {
		lego.LogError(err)
		return nil, err

	}

	//appwho.MiniAppId = miniAppIdForSale //TODO: 一般情况下，不允许修改who的值，但这里修改了，这里要考虑一下表的字段设计了
	permissionWho := common.NewWho(appwho.TenantId,miniAppIdForSale, appwho.Uid)
	var rcPermission *AppTenantPermission
	rcInDb := t.tbAppTenantPermission.RecodeWithSessionByAppWho(session, *permissionWho)
	if rcInDb == nil {
		rcPermission = new(AppTenantPermission)

		rcPermission.CheckMode = checkMode //common.APP_PERMISSION_CHECK_MODE_DATATIME //权限失效模式：以时间、以次数
		rcPermission.ExpireTime = utils.DateUtil(time.Now(), addTimeYmd) //如果是新建，过期时间是从当前开始算
		rcPermission.MiniAppId = miniAppIdForSale //<==这里是设置购买的mini app id
		rcPermission.TenantId = appwho.TenantId
		isSuccess := t.tbAppTenantPermission.AddRecodeWithsession(session, rcPermission)
		if !isSuccess {
			err = session.Rollback()
			if err != nil {
				lego.LogError(err)
				return nil, err

			}
			return nil, err
		}
	} else {
		//如果之前已经存在，且目前还未过期，则为旧的过期时间加上新增时长
		//如果目前已过期，则从当前时间开始计算
		m1 := rcInDb.ExpireTime.Month() //调试使用
		m2 := time.Now().Month() //调试使用
		m1 = m1 //调试使用
		m2 = m2 //调试使用

		if rcInDb.ExpireTime.After(time.Now()) {
			//未过期的情况
			rcInDb.ExpireTime = utils.DateUtil(rcInDb.ExpireTime, addTimeYmd)
		} else {
			//已过期的情况
			rcInDb.ExpireTime = utils.DateUtil(time.Now(), addTimeYmd)
		}

		isSuccess := t.tbAppTenantPermission.UpdateRecodeWithSessionByAppWho(session, rcInDb, *permissionWho)
		if !isSuccess {
			err = session.Rollback()
			if err != nil {
				lego.LogError(err)
				return nil, err

			}
			return nil, err
		}

		rcPermission = rcInDb

	}

	err = session.Commit()
	if err != nil {
		lego.LogError(err)
		return nil, err
	}

	return rcPermission, nil
}

func (t *AppTenantPermissionService) AddAppPermissionForAlwaysValid(appwho common.Who, miniAppIdForSale int64) error {
	rc := new(AppTenantPermission)
	rc.TenantId = appwho.TenantId
	rc.MiniAppId = miniAppIdForSale
	rc.CheckMode = common.APP_PERMISSION_CHECK_MODE_ALWAYS_VALID
	t.tbAppTenantPermission.AddRecode(rc)

	return nil
}

func (t *AppTenantPermissionService) CheckAppTenantPermission(appwho *common.Who) error {

	rcApp := t.tbAppTenantPermission.RecodeByWho(appwho)
	if rcApp == nil {
		//return errors.New("未开通APP")
		return fmt.Errorf("未开通APP, tid<%d> appid<%d>", appwho.TenantId, appwho.MiniAppId)
	}

	if rcApp.CheckMode == common.APP_PERMISSION_CHECK_MODE_DATATIME {
		if rcApp.ExpireTime.Before(time.Now()) {
			return errors.New("APP过期")
		}
	} else if rcApp.CheckMode == common.APP_PERMISSION_CHECK_MODE_TIMES {
		//根据次数
		if rcApp.UseTimes <= 0 {
			return errors.New("APP次数已经使用完")
		}
	} else if rcApp.CheckMode == common.APP_PERMISSION_CHECK_MODE_ALWAYS_VALID {
		return nil
	}

	return nil

}
